<template>
  <el-main>
      <div class="w-full flex flex-row gap-2 border-b-gray-300 border p-2">
        <el-input v-model="searchQuery" placeholder="动物名称" class="max-w-[200px]"></el-input>
        <el-select  v-model="FilterType" placeholder="种类" style="width: 200px" v-if="USER.role==='3'||USER.role==='4'" >
          <el-option
              v-for="item in TypeOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      <div>
        <el-button type="success" @click="FilterAnimal">查询</el-button>
        <el-button type="danger" @click="FilterReset">重置</el-button>
        <el-button @click="isFlag.dialogVisbaleCreateAnimal = true" type="warning">添加动物</el-button>


      </div>
    </div>
      <div class="w-full" style="overflow-y: auto;">
    <el-table :data="animallist" style="width: 100% " height="330"   @row-click="selectAnimal">
      <el-table-column prop="id" label="编号" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="type" label="类别" width="150" />
      <el-table-column prop="age" label="年龄"  width="150"/>
      <el-table-column prop="gender" label="性别"  width="150"/>
      <el-table-column prop="healthStatus" label="健康状态"  width="150">
        <template #default="scope">
            <el-tag type="success" v-if="scope.row.healthStatus === '1'">健康</el-tag>
            <el-tag type="warning" v-if="scope.row.healthStatus === '2'">受伤</el-tag>
            <el-tag type="danger" v-if="scope.row.healthStatus === '3'">肥胖</el-tag>
            <el-tag type="danger" v-if="scope.row.healthStatus === '4'">生病</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="nowWeight" label="当前体重"  width="150"/>
      <el-table-column prop="keeperId" label="饲养员编号" width="150" />
      <el-table-column prop="bornTime" label="出生时间" width="200" />
      <el-table-column label="操作" width="400">
        <template #default="scope">
          <div class="flex flex-row gap-1 w-[1000px]">
            <button class="bg-element-green text-white px-1 py-1 rounded-md hover:bg-element-hover-green"  @click="handleEdit(scope.row)"  @click.stop>编辑</button>
              <button class="bg-yellow-700  text-white px-1 py-1 rounded-md hover:bg-element-hover-green"@click="handleFeedPlan(scope.row)"  @click.stop>饲养计划</button>
            <button class="bg-yellow-500  text-white px-1 py-1 rounded-md hover:bg-element-hover-green"  @click="handleFeedfood(scope.row)"  @click.stop>投喂</button>
            <button class="bg-blue-500 text-white px-1 py-1 rounded-md hover:bg-element-hover-green"  @click="hanleMedical(scope.row)"  @click.stop>医疗预约</button>
              <el-popconfirm
                      confirm-button-text="是"
                      cancel-button-text="否"
                      :icon="InfoFilled"
                      icon-color="#626AEF"
                      title="你确认要删除吗？"
                      @confirm="remove(scope.row)"
                      @cancel="cancelEvent">
                  <template #reference>
                      <button class="bg-red-500 text-white px-2.5 py-1 rounded-md hover:bg-red-600"  @click.stop>删除</button>
                  </template>
              </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>
      </div>
      <div class="items-center h-[600px]">
          <div style="font-weight: bold; font-size: 25px;text-align: center ">
              该动物最近七个时间段体重变化（kg)
          </div>
          <v-chart class="w-[2000px] h-[600px]" :option="option" />
      </div>
      <!--    新增动物-->
      <el-dialog v-model="isFlag.dialogVisbaleCreateAnimal"  title="新增动物" width="500" center>
      <el-form :model="newAnimal">
        <el-form-item label="名称:" label-width="80px" >
          <el-input v-model="newAnimal.name" placeholder="请填写动物名称"></el-input>
        </el-form-item>
        <el-form-item label="年龄:" label-width="80px" >
          <el-input v-model="newAnimal.age"><template #append>年</template></el-input>
        </el-form-item>
        <el-form-item label="性别:" label-width="80px">
            <el-select  v-model="newAnimal.gender" placeholder="请选择"  size="large" style="width: 240px" >
                <el-option
                        v-for="item in GenderOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="健康状况:" label-width="80px">
            <el-select  v-model="newAnimal.healthStatus" placeholder="请选择"  size="large" style="width: 240px" >
                <el-option
                        v-for="item in HealthOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="当前体重:" label-width="80px"  >
          <el-input v-model="newAnimal.nowWeight" placeholder="请填写动物体重"><template #append>千克（Kg）</template></el-input>
        </el-form-item>
          <el-form-item label="类型:" label-width="80px" >
              <el-input v-model="newAnimal.type" @change="handleChange(newAnimal.type)" placeholder="请填写动物类型"></el-input>
          </el-form-item>
        <el-form-item  label="饲养员:" label-width="80px">
            <el-select @click="handleChange(newAnimal.type)" v-model="newAnimal.keeperId" placeholder="请选择" :disabled="newAnimal.type === ''" size="large" style="width: 240px" >
            <el-option
                v-for="item in KeeperOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期:" label-width="80px">
          <el-date-picker
              format="YYYY/MM/DD" value-format="YYYY-MM-DD" type="date"
              v-model="newAnimal.bornTime"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isFlag.dialogVisbaleCreateAnimal = false">取消</el-button>
          <el-button type="primary" @click="save" >确定</el-button>
        </div>
      </template>
    </el-dialog>
      <!-- 动物编辑窗口-->
      <el-dialog v-model="isFlag.dialogVisbaleEditAnimal"  title="编辑动物信息" width="500" center>
          <el-form :model="currentAnimal">
              <el-form-item label="名称:" label-width="80px">
                  <el-input v-model="currentAnimal.name" placeholder="请填写动物名称"
                  ></el-input>
              </el-form-item>
              <el-form-item label="类别:" label-width="80px">
                  <el-input v-model="currentAnimal.type" @change="handleChange(currentAnimal.type)" placeholder="请填写动物类别"></el-input>
              </el-form-item>
              <el-form-item label="年龄:" label-width="80px">
                  <el-input v-model="currentAnimal.age"></el-input>
              </el-form-item>
              <el-form-item label="性别" label-width="80px">
                  <el-select  v-model="currentAnimal.gender" placeholder="请选择"  size="large" style="width: 240px" >
                      <el-option
                              v-for="item in GenderOptions"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                      />
                  </el-select>
              </el-form-item>
              <el-form-item label="健康状态:" label-width="80px">
                  <el-select  v-model="currentAnimal.healthStatus" placeholder="请选择"  size="large" style="width: 240px" >
                      <el-option
                              v-for="item in HealthOptions"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                      />

                  </el-select>
              </el-form-item>
              <el-form-item label="入园体重:" label-width="80px"  >
                  <el-input v-model="currentAnimal.nowWeight" placeholder="请填写动物体重"><template #append>千克（Kg）</template></el-input>

              </el-form-item>
              <el-form-item label="饲养员:" label-width="80px">
                  <el-select @click="handleChange(currentAnimal.type)"  v-model="currentAnimal.keeperId" placeholder="请选择" size="large" style="width: 240px" >
                      <el-option
                              v-for="item in KeeperOptions"
                              :key="item.id"
                              :label="item.nickname"
                              :value="item.id"
                      />
                  </el-select>
              </el-form-item>
              <el-form-item label="出生日期:" label-width="80px">
                  <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" type="date" v-model="currentAnimal.bornTime" />
              </el-form-item>
          </el-form>
          <template #footer>
              <div class="dialog-footer">
                  <el-button @click="isFlag.dialogVisbaleEditAnimal = false">取消</el-button>
                  <el-button type="primary" @click="update">确定</el-button>
              </div>
          </template>
      </el-dialog>
      <!-- 投喂窗口-->
      <el-dialog v-model="isFlag.dialogVisbaleFeed"  title="投喂信息" width="500" center>
          <el-form >
            <el-form-item label="食物名称:" label-width="80px">
                  <el-input v-model="newfeedFood.foodName"  placeholder="名称不能为空"></el-input>
              </el-form-item>
            <el-form-item label="投喂重量:" label-width="80px">
                  <el-input v-model="newfeedFood.foodWeigh"  placeholder="重量不能为空"><template #append>千克（Kg）</template></el-input>
              </el-form-item>
          </el-form>
          <template #footer>
              <div class="dialog-footer">
                  <el-button @click="isFlag.dialogVisbaleFeed = false">取消</el-button>
                  <el-button type="primary" @click="saveFeedfood" >确定</el-button>
              </div>
          </template>
      </el-dialog>
      <!-- 医疗窗口-->
      <el-dialog v-model="isFlag.dialogVisbaleMedical"  title="医疗信息" width="500" center>
          <el-form >
              <el-form-item label="预约主题:" label-width="80px">
                  <el-input v-model="newmedical.applicationTitle"  placeholder="主题不能为空"></el-input>
              </el-form-item>
              <el-form-item label="具体描述:" label-width="80px">
                  <el-input type="textarea" :rows="10" v-model="newmedical.applicationDetail" style="height: 200px"></el-input>
              </el-form-item>
          </el-form>
          <template #footer>
              <div class="dialog-footer">
                  <el-button @click="isFlag.dialogVisbaleMedical = false">取消</el-button>
                  <el-button type="primary" @click="saveMedical">确定</el-button>
              </div>
          </template>
      </el-dialog>
      <!-- 饲养计划窗口-->
      <el-dialog v-model="isFlag.dialogVisbaleFeedplan"  title="饲养计划" width="600" center>
          <el-form >
              <el-form-item label="早饭饲养建议:" label-width="100px" >
                  <el-input type="textarea" v-model="FeedPlan.breakfast" :disabled="USER.job === '饲养员'"  style="height: 120px"></el-input>
              </el-form-item>
              <el-form-item label="午饭饲养建议:" label-width="100px" >
                  <el-input type="textarea" v-model="FeedPlan.lunch" :disabled="USER.job === '饲养员'" style="height: 120px"></el-input>
              </el-form-item>
              <el-form-item label="晚饭饲养建议:" label-width="100px"  >
                  <el-input type="textarea" v-model="FeedPlan.dinner" :disabled="USER.job === '饲养员'" style="height: 120px"></el-input>
              </el-form-item>

          </el-form>
          <template #footer>
              <div class="dialog-footer">
                  <el-button @click="isFlag.dialogVisbaleFeedplan = false">退出</el-button>
                  <el-button type="primary" v-if="USER.role==='3'||USER.role==='4'" @click="saveFeedPlan">修改</el-button>
              </div>
          </template>
      </el-dialog>
  </el-main>
</template>
<script setup lang="ts">
import {reactive, ref, toRef} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
const isFlag = reactive({
    dialogVisbaleCreateAnimal: false,
    dialogVisbaleEditAnimal: false,
    dialogVisbaleFeed: false,
    dialogVisbaleMedical:false,
    dialogVisbaleFeedplan:false
})
const animallist = ref([]);
const userlist =ref([]);
const currentAnimal = reactive({});
const KeeperOptions =ref({});
const FilterType =ref();
const searchQuery = ref();
const filteredList = ref([]);
const newAnimal = reactive({
  id:'',
  name:'',
  type:'',
  age:'',
  gender:'',
  healthStatus:'',
  startWeight:'',
  keeperId:'',
  bornTime:'',
  nowWeight:'',
})
let newfeedFood = reactive({
  animalId:'',
  keeperId:'',
  foodName:'',
  foodWeigh:'',
  animalAddWeigh:'',
})
let newmedical = reactive({
  animalId:'',
  keeperId:'',
  applicationTitle:'',
  applicationDetail:'',
})

const feedPlan = [
    {
        value:'雄',
        label:'雄',
    },
    {
        value:'雌',
        label:'雌',
    },

]

const TypeOptions = ref({})

const HealthOptions = [
    {
        value:'1',
        label:'健康',
    },
    {
        value:'2',
        label:'受伤',
    },
    {
        value:'3',
        label:'肥胖',
    },
    {
        value:'4',
        label:'生病',
    }
]

const GenderOptions = [
    {
        value:'雄',
        label:'雄',
    },
    {
        value:'雌',
        label:'雌',
    },
    {
        value:'未知',
        label:'未知',
    },
]

const USER=JSON.parse(localStorage.getItem('user'));
function init(){
  axios.get('http://localhost:8080/animal/getlist/byuseridfilter?id='+USER.id)
      .then(request =>{
        animallist.value = request.data
        filteredList.value = request.data
        console.log(animallist.value);

      })
  axios.get('http://localhost:8080/user/getlist')
      .then(request =>{
        userlist.value = request.data
        console.log(userlist);
      })
  axios.get('http://localhost:8080/animal/gettype')
      .then(request =>{
        console.log(request.data)
        TypeOptions.value=request.data;
        console.log(TypeOptions)
      })
}
init();

// 表单验证函数，确保名称和体重不为空且不包含特殊字符
function validateForm(tmpAnimal): boolean {
    if (tmpAnimal.name.trim() === '') {
        showErrorMessage('名称不能为空');
        return false;
    }
    if (checkSpecialCharacters(tmpAnimal.name)) {
        showErrorMessage('名称不能包含特殊字符');
        return false;
    }
    if (tmpAnimal.type.trim() === '') {
        showErrorMessage('动物类别不能为空');
        return false;
    }
    if (checkSpecialCharacters(tmpAnimal.type)) {
        showErrorMessage('动物类别不能包含特殊字符');
        return false;
    }
    if (tmpAnimal.nowWeight.toString().trim() === '') {
        showErrorMessage('当前体重不能为空');
        return false;
    }
    if (isNaN(parseFloat(tmpAnimal.nowWeight))) {
        showErrorMessage('当前体重必须是数字');
        return false;
    }



    return true;
}

// 检查字符串是否包含特殊字符的函数
function checkSpecialCharacters(input: string): boolean {
    // 此处可以根据需要定义特殊字符的规则，例如只允许中英文和数字，不允许特殊符号等
    const pattern = /[!@#$%^&*()+\=\[\]{};':"\\|,.<>\/?~]/;
    return pattern.test(input);
}

// 显示错误信息的弹窗
function showErrorMessage(message: string) {
    ElMessageBox.alert(message, '提示', {
        confirmButtonText: '确定',
    });
}
//新增
function save(){
    // 检查表单是否通过验证
    if (!validateForm(newAnimal)) {
        return; // 如果表单验证不通过，直接返回，不继续保存操作
    }
      newAnimal.startWeight=newAnimal.nowWeight;
    axios.post('http://localhost:8080/animal/save', newAnimal)
        .then(request => {
            console.log(request.data);
            if (request.data) {
                ElMessage({
                    message: '添加成功',
                    type: 'success'
                });
                isFlag.dialogVisbaleCreateAnimal = false;
                init(); // 如果需要重新初始化数据，调用 init() 方法
            }
        })
        .catch(error => {
            console.error('保存失败：', error);
            ElMessage({
                message: '保存失败，请重试',
                type: 'error'
            });
        });
}

//修改/更新

function update(){
  console.log(currentAnimal)
    // 前端验证
    if (!validateForm(currentAnimal)) {
        return; // 如果表单验证不通过，直接返回，不继续保存操作
    }
    axios.post('http://localhost:8080/animal/update', currentAnimal)
        .then(request => {
            console.log(request.data);
            if (request.data) {
                ElMessage({
                    message: '修改成功',
                    type: 'success'
                });
                isFlag.dialogVisbaleEditAnimal = false;
                init();
            }
        })
        .catch(error => {
            console.error('保存失败：', error);
            ElMessage({
                message: '保存失败，请重试',
                type: 'error'
            });
        });
}

function handleEdit (animal){
    Object.assign(currentAnimal,animal)
    //currentAnimal = animal
    isFlag.dialogVisbaleEditAnimal = true;
    console.log(currentAnimal)
}
function handleChange(type){
  KeeperOptions.value = '';
  KeeperOptions.value=userlist.value.filter(item => item.type===type && item.job==="饲养员");
  console.log(KeeperOptions)
}


function FilterAnimal (){
    axios.get('http://localhost:8080/animal/getlist/byuseridfilter?id='+USER.id)
      .then(request =>{
        filteredList.value = request.data
        if(FilterType.value!=null){
          filteredList.value=filteredList.value.filter(item =>item.type === FilterType.value)}
        if(searchQuery.value!=null){
          filteredList.value=filteredList.value.filter(item => {
            return item.name.includes(searchQuery.value);
          });}
        animallist.value=filteredList.value;
      })
  console.log(filteredList);
}

function remove(animal) {
    axios.post('http://localhost:8080/animal/remove',animal)
        .then(request =>{
            console.log(request.data)
            if (request.data){
                ElMessage({
                    message:'删除成功',
                    type:'success'
                })
                location.reload()
            }
        })
}
function handleFeedfood(animal){
  newfeedFood.foodName='';
  newfeedFood.foodWeigh='';
  newfeedFood.animalId=animal.id;
  newfeedFood.keeperId=animal.keeperId;
  newfeedFood.animalNowWeigh=animal.nowWeight;
  isFlag.dialogVisbaleFeed = true
}



// 表单验证函数，确保名称和体重不为空且不包含特殊字符
function validateFormFeed(tmpAnimal): boolean {
    if (tmpAnimal.foodName.trim() === '') {
        showErrorMessage('食物名称不能为空');
        return false;
    }
    if (checkSpecialCharacters(tmpAnimal.foodName)) {
        showErrorMessage('食物名称不能包含特殊字符');
        return false;
    }
    if (tmpAnimal.foodWeigh.trim() === '') {
        showErrorMessage('食物重量不能为空');
        return false;
    }
    if (checkSpecialCharacters(tmpAnimal.foodWeigh)) {
        showErrorMessage('食物重量不能包含特殊字符');
        return false;
    }

    return true;
}
function saveFeedfood(){
    // 检查表单是否通过验证
    if (!validateFormFeed(newfeedFood)) {
        return; // 如果表单验证不通过，直接返回，不继续保存操作
    }

    axios.post('http://localhost:8080/feed/save', newfeedFood)
        .then(request => {
            console.log(request.data);
            if (request.data) {
                ElMessage({
                    message: '添加成功',
                    type: 'success'
                });
                isFlag.dialogVisbaleFeed = false;
                init(); // 如果需要重新初始化数据，调用 init() 方法
            }
        })
        .catch(error => {
            console.error('保存失败：', error);
            ElMessage({
                message: '保存失败，请重试',
                type: 'error'
            });
        });
}
function hanleMedical(animal){
  newmedical.applicationDetail='';
  newmedical.applicationTitle='';

  isFlag.dialogVisbaleMedical=true
  newmedical.animalId=animal.id;
  newmedical.keeperId=animal.keeperId;
}


const FeedPlanlist = ref({});
let FeedPlan=reactive({
    id:'',
    animalId:'',
    breakfast:'',
    lunch:'',
    dinner:'',

})

function handleFeedPlan(animal){
    axios.get('http://localhost:8080/feedplan/getplan',{params: { id: animal.id }})
        .then(request =>{
            FeedPlanlist.value = request.data
            FeedPlan.animalId=animal.id
            FeedPlan.id=request.data.id
            FeedPlan.breakfast=request.data.breakfast||'无建议'
            FeedPlan.lunch=request.data.lunch||'无建议'
            FeedPlan.dinner=request.data.dinner||'无建议'
        })


    isFlag.dialogVisbaleFeedplan=true

}

function saveFeedPlan(){
    axios.post('http://localhost:8080/feedplan/setplan',FeedPlan)
        .then(request =>{
            console.log(request.data)
            if (request.data){
                ElMessage({
                    message:'添加成功',
                    type:'success'
                })
                isFlag.dialogVisbaleFeedplan = false

            }
        })
}

// 表单验证函数，确保主题不为空且不包含特殊字符
function validateFormMedical(tmpAnimal): boolean {
    if (tmpAnimal.applicationTitle.trim() === '') {
        showErrorMessage('预约主题不能为空');
        return false;
    }
    if (checkSpecialCharacters(tmpAnimal.applicationTitle)) {
        showErrorMessage('预约主题不能包含特殊字符');
        return false;
    }
    return  true
}







function saveMedical(){
    // 检查表单是否通过验证
    if (!validateFormMedical(newmedical)) {
        return; // 如果表单验证不通过，直接返回，不继续保存操作
    }
    axios.post('http://localhost:8080/medical/save',newmedical)
        .then(request =>{
            console.log(request.data)
            if (request.data){
                ElMessage({
                    message:'添加成功',
                    type:'success'
                })
                isFlag.dialogVisbaleMedical = false
                init();
            }
        })
        .catch(error => {
            console.error('保存失败：', error);
            ElMessage({
                message: '保存失败，请重试',
                type: 'error'
            });
        });

}
function FilterReset(){
  location.reload();
}


function selectAnimal(animalId){
    axios.get('http://localhost:8080/watch/getlist',{params: { id: animalId.id }})
        .then((response =>{
                option.value.series[0].data = response.data
             console.log(option.value.series[0].data)
        })
        )

}


import { use } from 'echarts/core'
import { LineChart } from 'echarts/charts'
import { GridComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

use([GridComponent, LineChart, CanvasRenderer])
import VChart, { THEME_KEY } from "vue-echarts";
import { ref } from "vue";

  const option = ref({
      xAxis: {
          type: 'category',
          data: ['一', '二', '三', '四', '五', '六', '七'],
      },
      yAxis: {
          type: 'value'
      },
      series: [
          {
              data: [0],
              type: 'line'
          }
      ]
  });


</script>


